/**
 * Created by joy on 03/09/2017.
 */

import BitcoinCashWalletHelper from '../../common/helpers/chain/BitcoinCashWalletHelper'
import CommonUtil from '../../common/utils/CommonUtil'
import prompt from 'prompt'
import fs from 'fs'
import lineReader from 'line-reader'

export default () => {
  return new Promise(async (resolve, reject) => {
    try {
      const bitcoinCashWalletHelper = new BitcoinCashWalletHelper()
      const schema = {
        properties: {
          xpriv: {
            description: 'Enter your master private key',
            type: 'string',
            required: true
          },
          fee: {
            description: 'Enter network fee for every tx',
            type: 'number',
            required: true,
            default: 0.0005
          },
          input: {
            description: 'Enter unsigned filename',
            type: 'string',
            required: true,
            default: 'temp_data/unsigned.txt'
          },
          output: {
            description: 'Enter filename to save result',
            type: 'string',
            required: true,
            default: 'temp_data/signed.txt'
          },
          network: {
            description: 'Enter network type',
            type: 'string',
            required: true,
            default: 'bitcoin'
          },
          toAddress: {
            description: 'Enter address you want to send to',
            type: 'string',
            required: true
          }
        }
      }

      const args = await CommonUtil.getArgsFromConsole(prompt, schema)
      const { xpriv, fee, input, output, network, toAddress } = args
      // console.log(args)
      let results = []
      lineReader.eachLine(input, async (line, last) => {
        try {
          const inputs = JSON.parse(line)
          // logger.error('inputs', inputs)
          const utxos = []
          for (let input of inputs) {
            const { txid, index, amount, path, address } = input
            const privateKey = bitcoinCashWalletHelper.getPrivateKeyByPath(xpriv, path)
            // logger.error('privateKey', privateKey)
            utxos.push({
              utxoTxId: txid,
              utxoOutputIndex: index,
              utxoBalance: bitcoinCashWalletHelper.toSatoshi(amount),
              privateKey: privateKey
            })
          }
          const result = await bitcoinCashWalletHelper.buildAndDistributeTx(
            utxos,
            toAddress,
            bitcoinCashWalletHelper.toSatoshi(1),
            30,
            bitcoinCashWalletHelper.toSatoshi(fee),
            network
          )
          // logger.error(result)
          results.push(result)
          if (last) {
            CommonUtil.delFileSync(output)
            results.map((result) => {
              fs.appendFileSync(output, JSON.stringify(result) + '\n')
            })
            resolve()
          }
        } catch (err) {
          logger.error(err)
          reject(err)
        }
      })
    } catch (err) {
      logger.error(err)
      reject(err)
    }
  })

}
